import { defineStore } from "pinia";
import auth from "@/plugins/auth";
import router, { constantRoutes, dynamicRoutes } from "@/router";
import { getRouters } from "../api/router";
import { queryModuleType } from "../api/system/moduleInfo/api.js";
import { getRouterTree } from "../utils/ruoyi";
import Layout from "@/layout/index";
import ParentView from "@/components/ParentView";

export const usePermissionStore = defineStore("permission", {
  state: () => ({
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: [],
    sidebarChildRouters: [],
    activeParentsRouter: "",
    activeTopRouter: "",
    sidebarRouterssw: [],
  }),
  actions: {
    // 生成路由
    async generateRoutes() {
      try {
        // 向后端请求路由数据
        const res = await getRouters({ moduleTypeStr: "-2" });

        // 转为树状结构
        let routerTree = getRouterTree(res.result, "parentId", "id");

        const moduleTypeRes = await queryModuleType();
        let moduleTypeList = moduleTypeRes.result.data || [];

        // 将菜单树按模块类型分组
        let flRouter = {};
        let notTypeRouter = [];
        routerTree.forEach((item, index) => {
          let moduleTypeUnid = item.meta.moduleTypeUnid;
          if (moduleTypeUnid != null) {
            if (!flRouter[moduleTypeUnid]) {
              flRouter[moduleTypeUnid] = [];
            }
            flRouter[moduleTypeUnid].push(item);
          } else {
            notTypeRouter.push(item);
          }
        });

        // 重新组合路由树
        let allRouterTree = [];
        moduleTypeList.forEach((pre_type) => {
          let children = flRouter[pre_type.unid];
          if (children != null && children.length > 0) {
            allRouterTree.push({
              component: "Layout",
              name: pre_type.path + "_layout",
              path: pre_type.path + "_layout",
              children: children,
              redirect: children[0].path,
              meta: {
                title: pre_type.typeCommonname,
                icon: pre_type.icon || "list",
                moduleTypeUnid: pre_type.unid,
              },
            });
          }
        });
        notTypeRouter.forEach((pre_route) => {
          allRouterTree.push(pre_route);
        });

        const sdata = JSON.parse(JSON.stringify(allRouterTree));
        const rdata = JSON.parse(JSON.stringify(allRouterTree));

        // 获取 app store 状态
        const appStore = useAppStore();
        const settingsStore = useSettingsStore();

        const sidebarRoutes = filterAsyncRouter(
          sdata,
          false,
          false,
          appStore.noShowLayout
        );
        const rewriteRoutes = filterAsyncRouter(
          rdata,
          false,
          true,
          appStore.noShowLayout
        );

        const asyncRoutes = dynamicRoutes;
        rewriteRoutes.push({ path: "*", redirect: "/404", hidden: true });

        // 添加动态路由
        asyncRoutes.forEach((route) => {
          router.addRoute(route);
        });

        this.routes = [...constantRoutes, ...rewriteRoutes];
        this.addRoutes = rewriteRoutes;

        // 判断是否开启顶部导航栏
        if (!settingsStore.topNav) {
          this.sidebarRouters = [...constantRoutes, ...sidebarRoutes];
        }

        this.defaultRoutes = sidebarRoutes;
        this.topbarRouters = sidebarRoutes;

        return rewriteRoutes;
      } catch (error) {
        console.error("路由生成失败:", error);
        throw error;
      }
    },
  },
});

// 遍历后台传来的路由字符串，转换为组件对象
export function filterAsyncRouter(
  asyncRouterMap,
  lastRouter = false,
  type = false,
  isNoShowLayout
) {
  return asyncRouterMap.filter((route) => {
    if (type && route.children) {
      route.children = filterChildren(route.children);
    }
    if (route.component) {
      route.componentStr = route.component;
      // Layout ParentView 组件特殊处理
      if (route.component === "Layout") {
        // isNoShowLayout 是否显示导航栏和侧边栏
        // 作为热点挂职到其他系统时需要 隐藏导航栏和侧边栏
        if (isNoShowLayout) {
          route.component = ParentView;
        } else {
          route.component = Layout;
        }
      } else if (route.component === "RouteView") {
        route.component = ParentView;
      } else {
        route.component = loadView(route.component);
      }
    }
    if (route.children != null && route.children && route.children.length) {
      // 添加重定向
      for (var child = 0; child < route.children.length; child++) {
        if (route.children[child].meta && route.children[child].meta.show) {
          route.redirect = route.children[child].path;
          break;
        }
      }
      route.children = filterAsyncRouter(
        route.children,
        route,
        type,
        isNoShowLayout
      );
    } else {
      delete route["children"];
      delete route["redirect"];
    }
    return true;
  });
}

export function filterChildren(childrenMap, lastRouter = false) {
  var children = [];
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === "ParentView" && !lastRouter) {
        el.children.forEach((c) => {
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c));
            return;
          }
          children.push(c);
        });
        return;
      }
    }
    children = children.concat(el);
  });
  return children;
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = [];
  routes.forEach((route) => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route);
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route);
      }
    }
  });
  return res;
}

export const loadView = (view) => {
  // 处理路径斜杠
  let tampFh = "/";
  if (view.indexOf("/") == 0) {
    tampFh = "";
  }

  // 处理特殊路径
  if (view == "module/newHCView/CommonForm") {
    view = "module/HCView/CommonForm";
  }
  if (view == "module/newHCView/CommonView") {
    view = "module/HCView/CommonView";
  }

  if (process.env.NODE_ENV === "development") {
    return (resolve) => require([`@/views${tampFh}${view}`], resolve);
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views${tampFh}${view}`);
  }
};

// 导入其他 store
import { useAppStore } from "./app";
import { useSettingsStore } from "./settings";
